import { forIn } from "lodash"

/**
 * 等待一定时间后继续执行（async中
 * @param time 等待时间
 * @returns a Promise
 */
export const timeSleep = (time:number) => {
  return new Promise(success=>{
    setTimeout(()=>{
      success('')
    },time)
  })
}

/**
 * 打招呼
 */
export const hello = (uname) => {
	const h = new Date().getHours();
	let str = `哦亲爱的 ${uname} ，`
	if(h <= 4 || h >= 23) str += '夜深了，早些歇息吧。'
	else if(h >= 5 && h<= 11) str += '早上好，今天也是元气满满的一天呢。'
	else if(h >= 12 && h<= 15) str += '中午好，今天午休了吗？'
	else if(h >= 16 && h<= 19) str += '下午好，晚上吃点啥呢？'
	else if( h>= 19 && h<= 22) str += '晚上好，要一起去看月亮嘛。'
	return str
}

/**
 * 邮箱验证
 * @param mail 邮箱
 * @returns Boolean
 */
export const mailReg = (mail:string) => {
	return mail!=''?
	/^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/.test(mail)
	: true
}

/**
 * @param fmt 
 * @param date 
 * @returns 
 */
export const dateFormat = (date:Date|string|number,fmt:string) =>{
  let ret;
  if(!date) return ''
  // Object.prototype.toString.call(date) != '[object Date]'
  if(!(date instanceof Date)) date = new Date(date)
  if(!fmt) fmt = 'YYYY-MM-DD hh:mm'
  const opt = {
      "Y+": date.getFullYear().toString(),        // 年
      "M+": (date.getMonth() + 1).toString(),     // 月
      "D+": date.getDate().toString(),            // 日
      "h+": date.getHours().toString(),           // 时
      "m+": date.getMinutes().toString(),         // 分
      "s+": date.getSeconds().toString()          // 秒
  };
  for (let k in opt) {
      ret = new RegExp("(" + k + ")").exec(fmt);
      if (ret) {
          fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
      };
  };
  return fmt;
}

/**
 * 补0
 * @param num 要补充的数字
 * @param cover 补充到多少位？
 * @returns String
 */
export const replenish = (num, cover, tag) => {
  num = String(num)
  if(String(num).length > cover)
    return String(num)
  return num = tag.repeat(cover).concat(num).slice(-cover)
}
  

/**
 * 正则们
 * 
 */
export const regs = {
  account: /^[1-9]{8,16}$/,
  phoneNumber:/^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/,
  email:/[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
  name: /^[\u4E00-\u9FA5A-Za-z]{2,}$/,
  idcard:/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
  qq:/^[1-9][0-9]{4,14}$/,
  //数字+字母、8~16
  pass:/^(?=.*[0-9])(?=.*[a-zA-Z])[0-9A-Za-z~!@#$%^&*._?]{6,12}$/,
  wechat:/^[a-zA-Z][a-zA-Z\d_-]{5,19}$/,
}

/**
 * 上传图片
 * @param file 文件
 * @returns 
 */ 
export const uploadFile = async file => {

}


/**
 * File => String
 */
 export const FileToBase64 = file => {
  return new Promise((resolve, reject) => {
      const reader = new FileReader()
      let fileResult = ""
      reader.readAsDataURL(file)
      reader.onload = () => { fileResult = reader.result }
      reader.onerror = error => reject(error)
      reader.onloadend = () => resolve(fileResult)
  })
}

/**
 * url(http) -> base64
 */
export const urlToBase64 = (imgsrc) => {
  return new Promise((ok,no)=>{
    const image = new Image()
    image.setAttribute("crossOrigin", "anonymous")
    image.onload = function() {
      const canvas = document.createElement("canvas");
      canvas.width = image.width;
      canvas.height = image.height;
      const context = canvas.getContext("2d");
      context.drawImage(image, 0, 0, image.width, image.height);
      const base64_str = canvas.toDataURL("image/png")
      ok(base64_str)
    }
    image.src = imgsrc
  })
}

/**
 * 下载base64
 */
export const exportFile = (base64_str,fileName) =>{
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = base64_str
  link.setAttribute('download', fileName)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  window.URL.revokeObjectURL(base64_str)
}


/**
 * return required rules
 */
export const requiredRules = (requiredlist={},{addtext,trigger}) => {
  addtext = addtext || '不能为空'
  trigger = trigger || 'blur'
  const rules = {}
  forIn(requiredlist,(value,key)=>{
    rules[key] = { required:true, message:`${value}${addtext}`, trigger}
  })
  return rules
}


/**
 * base64图片加水印
 */
// import WaterMark from 'l-watermark'
export const addwatermark = ({target,text}) => new Promise((ok)=>{
  WaterMark.image({
    target,
    text,
    color: "rgba(0, 0, 0, 0.4)",
    fontSize: 28,
    cSpace:60,
    // secret: true,
    success:(e)=>{
      ok(e)
    }
  })
})


/**
 * base64转File
 */

export const base64ToFile = (dataurl,filename="图片.png") => {
  const arr = dataurl.split(',')
  const mime = arr[0].match(/:(.*?);/)[1]
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
}

/**
 * 输出警告的HTML代码段
 */
export const getWarnHtmlStr = text => 
  `<span class="text-red-500 font-bold">${text}</span>`
